package com.hqyj.springCloundAccount.server.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.account.entity.Role;
import com.hqyj.commom.vo.Result;
import com.hqyj.commom.vo.Search;
import com.hqyj.springCloundAccount.dao.RoleDao2;
import com.hqyj.springCloundAccount.dao.RoleResourceDao2;
import com.hqyj.springCloundAccount.dao.UserRoleDao2;
import com.hqyj.springCloundAccount.server.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao2 roleDao2;
    @Autowired
    private UserRoleDao2 userRoleDao2;
    @Autowired
    private RoleResourceDao2 roleResourceDao2;



    @Override
    @Transactional
    public Result<Role> addRole(Role role) {
        role.setCreateDate(LocalDateTime.now());
        role.setUpdateDate(LocalDateTime.now());
        roleDao2.addRole(role);

        return new Result<Role>(Result.ResultStatus.SUCCESS.code, "角色添加成功!",role);

    }

    @Override
    @Transactional
    public Result<Role> updateRole(Role role) {
        role.setUpdateDate(LocalDateTime.now());
         roleDao2.updateRole(role);
         return new Result<Role>(Result.ResultStatus.SUCCESS.code, "角色修改成功!",role);
    }

    @Override
    @Transactional
    public Result<Object> deleteRoleById(int id) {
        roleDao2.deleteRoleById(id);
        userRoleDao2.deleteUserRoleByRoleId(id);
        roleResourceDao2.deleteRoleResourceByRoleId(id);
        return new Result<Object>(Result.ResultStatus.SUCCESS.code, "角色删除成功!");


    }

    @Override
    public Role getRoleById(int id) {
        return roleDao2.getRoleByRoleId(id);
    }

    @Override
    public List<Role> getRolesByUserId(int userId) {
        return Optional.ofNullable(roleDao2.getRolesByUserId(userId)).orElse(Collections.emptyList());
    }

    @Override
    public List<Role> getRoles() {
        return roleDao2.getRoles();
    }

    @Override
    public PageInfo<Role> getRolesBySearchBean(Search search) {
        search.init();
        PageHelper.startPage(search.getCurrentPage(),search.getPageSize());
        return new PageInfo<Role>(Optional.ofNullable(roleDao2.getRolesBySearch(search))
                .orElse(Collections.emptyList()));
    }


}
